package com.design.strategy.deep;

import lombok.Data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 深克隆，必须实现序列化接口才能实现对象的读写操作
 * @Author:         cong zhi
 * @CreateDate:     2021/3/20 17:42
 * @UpdateUser:     cong zhi
 * @UpdateDate:     2021/3/20 17:42
 * @UpdateRemark:   修改内容
 * @Version:        1.0
 */
@Data
public class ConcretePrototype implements Cloneable , Serializable {

    private int age;
    private String name;


    private List<String> hobbies;

    public List<String> getHobbies() {
        return hobbies;
    }


    @Override
    public ConcretePrototype clone() {
        try {
            // clone 对象
            return (ConcretePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public ConcretePrototype deepClone() {
        try {
            // 首先将对象变成字节流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (ConcretePrototype) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public ConcretePrototype deepCloneHobbies() {
        try {
            ConcretePrototype result = (ConcretePrototype)super.clone();
            result.hobbies = (List)((ArrayList) result.hobbies).clone();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String toString() {
        return "ConcretePrototype{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", hobbies=" + hobbies +
                '}';
    }
}
